package org.simple_blogging;

import java.util.Date;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import com.google.appengine.api.datastore.Key;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class BlogEntry {
	
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key pKey;
	
	@Persistent
	private Date dateSaved;
	
	@Persistent
	private String title;
	
	@Persistent
	private String text;
	
	private SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
	
	public BlogEntry(String blogTitle, String blogText, String dateSubmitted)
	{
		title = blogTitle;
		text = blogText;
		try {
			dateSaved = dateFormat.parse(dateSubmitted);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	
	public String getBlogTitle()
	{
		return title;
	}
	
	public String getBlogText()
	{
		return text;
	}
	
	public Date getDateSubmitted()
	{
		return dateSaved;
	}
	
	public String getDateSubmittedString()
	{
		String myDate = dateFormat.format(dateSaved);
		//return dateFormat.format(dateSaved);
		return dateSaved.toString();
	}
	
	public boolean addToDataStore()
	{		
		PersistenceManager pm = PersistenceManagerFac.getInstance().getPersistenceManager();

		Transaction tx = pm.currentTransaction();
		
		try{
			tx.begin();
			
			pm.makePersistent(this);
			
			tx.commit();
		}
		finally
		{
			if(tx.isActive())
			{
				tx.rollback();
				return false;
			}
		}
		return true;
	}
}
